package com.filter;

import com.model.TestUser;
import com.service.TestUserService;
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.context.support.WebApplicationContextUtils;

/**
 * Created by Administrator on 2018-8-18 0018.
 */
public class UserLoginFilter implements Filter {


    public UserLoginFilter() {

    }

    @Override
    public void destroy() {

    }

    private TestUserService testUserService;

    @Override
    public void doFilter(ServletRequest req, ServletResponse rsp, FilterChain filterChain) throws IOException, ServletException {

        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) rsp;
        HttpSession session = request.getSession();

        String uri = request.getRequestURI();

        TestUser user = (TestUser) session.getAttribute("loginSuccess");
        if (user == null || uri.indexOf("/userManage/") == -1) {
            request.getRequestDispatcher("/home/login").forward(req, rsp);
            return;
        }
        if (StringUtils.isNotBlank(user.getUserName())) {
            //user = testUserService.getUserByName(user.getUserName());
            request.setAttribute("title","主页");
            response.sendRedirect("/home/toIndex");
            return;
        } else {
            filterChain.doFilter(request, response);
        }
    }

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        testUserService = WebApplicationContextUtils.getWebApplicationContext(filterConfig.getServletContext()).getBean(TestUserService.class);
    }

}
